<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket摄像头视频流</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.5.2/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        
        .container {
            background-color: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            padding: 30px;
            width: 100%;
            max-width: 800px;
            text-align: center;
        }
        
        h1 {
            color: #333;
            margin-bottom: 30px;
            font-size: 2.2em;
            font-weight: 700;
        }
        
        .video-container {
            background-color: #000;
            border-radius: 10px;
            overflow: hidden;
            margin: 30px 0;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
        
        canvas {
            display: block;
            width: 100%;
            height: auto;
            border-radius: 10px;
        }
        
        .controls {
            margin: 20px 0;
        }
        
        .btn {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border: none;
            padding: 20px 40px;
            font-size: 1.2em;
            font-weight: 600;
            border-radius: 50px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 5px 15px rgba(79, 172, 254, 0.4);
            outline: none;
            margin: 10px;
        }
        
        .btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(79, 172, 254, 0.6);
        }
        
        .btn:active {
            transform: translateY(-1px);
            box-shadow: 0 3px 10px rgba(79, 172, 254, 0.5);
        }
        
        .status {
            margin-top: 20px;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 8px;
            font-size: 0.9em;
            color: #666;
            min-height: 50px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .loading {
            display: none;
            margin-top: 10px;
            color: #4facfe;
        }
        
        .loading.active {
            display: block;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 20px;
            }
            
            h1 {
                font-size: 1.8em;
            }
            
            .btn {
                padding: 15px 30px;
                font-size: 1em;
                width: 100%;
                max-width: 300px;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <h1>WebSocket实时摄像头视频流</h1>

    <div class="video-container">
        <canvas id="videoCanvas" width="640" height="480"></canvas>
    </div>

    <div class="controls">
        <button id="startBtn" class="btn" onclick="startStream()">开始视频流</button>
        <button id="stopBtn" class="btn" onclick="stopStream()" disabled>停止视频流</button>
    </div>

    <div class="status" id="status">
        请点击"开始视频流"按钮启动摄像头
    </div>

    <div class="loading" id="loading">
        <p>正在连接摄像头...</p>
    </div>
</div>

<script>
    let stompClient = null;
    const canvas = document.getElementById('videoCanvas');
    const ctx = canvas.getContext('2d');
    const status = document.getElementById('status');
    const loading = document.getElementById('loading');
    const startBtn = document.getElementById('startBtn');
    const stopBtn = document.getElementById('stopBtn');
    let isStreaming = false;

    function startStream() {
        if (isStreaming) return;

        // 更新UI状态
        startBtn.disabled = true;
        stopBtn.disabled = false;
        status.textContent = "正在初始化视频流...";
        loading.classList.add('active');

        // 清空画布并显示加载提示
        ctx.fillStyle = '#000';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = '#fff';
        ctx.font = '20px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('正在加载摄像头...', canvas.width / 2, canvas.height / 2);

        // 启动视频流服务
        fetch('/camera/startStream')
            .then(response => response.text())
            .then(data => {
                console.log('Stream started:', data);

                // 连接WebSocket
                const socket = new SockJS('/camera/ws');
                stompClient = Stomp.over(socket);

                stompClient.connect({}, function(frame) {
                    console.log('Connected to WebSocket:', frame);
                    isStreaming = true;
                    status.textContent = "视频流已连接，正在接收图像...";
                    loading.classList.remove('active');

                    stompClient.subscribe('/topic/videoStream', function(message) {
                        const image = new Image();
                        image.onload = function() {
                            ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
                            if (status.textContent.includes("正在接收图像")) {
                                status.textContent = "视频流正常运行中";
                            }
                        };
                        image.onerror = function() {
                            status.textContent = "图像加载失败，请检查摄像头连接";
                        };
                        image.src = 'data:image/jpeg;base64,' + message.body;
                    });
                });

                stompClient.onerror = function(error) {
                    console.error('WebSocket error:', error);
                    status.textContent = "WebSocket连接错误: " + error;
                    loading.classList.remove('active');
                    resetUI();
                };

                stompClient.onclose = function() {
                    console.log('WebSocket connection closed');
                    if (isStreaming) {
                        status.textContent = "WebSocket连接已关闭";
                        resetUI();
                    }
                };

            })
            .catch(error => {
                console.error('Error starting stream:', error);
                status.textContent = "启动视频流失败: " + error.message;
                loading.classList.remove('active');
                resetUI();
            });
    }

    function stopStream() {
        if (!isStreaming) return;

        // 关闭WebSocket连接
        if (stompClient) {
            stompClient.disconnect();
            stompClient = null;
        }

        isStreaming = false;
        resetUI();

        // 清空画布
        ctx.fillStyle = '#000';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = '#fff';
        ctx.font = '20px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('视频流已停止', canvas.width / 2, canvas.height / 2);

        status.textContent = "视频流已停止，请点击'开始视频流'重新启动";
    }

    function resetUI() {
        isStreaming = false;
        startBtn.disabled = false;
        stopBtn.disabled = true;
        loading.classList.remove('active');
    }

    // 页面关闭时清理资源
    window.addEventListener('beforeunload', function() {
        stopStream();
    });
</script>
</body>
</html>